package com.eflyme.learn.nc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ucar.ma2.Array;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.NetcdfFile;
import ucar.nc2.NetcdfFiles;
import ucar.nc2.Variable;
import ucar.nc2.write.Ncdump;

import java.io.IOException;
import java.util.Objects;

/**
 * @author LiShixi 2021/2/3 3:13 下午
 * @email loyy77@163.com
 */
public class NcRead {
    private static Logger logger = LoggerFactory.getLogger(NcWrite.class);

    public static String read(String ncFile, String sectionSpec) {
        try (NetcdfFile netcdfFile = NetcdfFiles.open(ncFile)) {
            final Variable tem = netcdfFile.findVariable("TEM");
            if (Objects.isNull(tem)) {
                logger.warn("变量不存在：TEM");
                return "";
            }
            try {
                // sectionSpec is string specifying a range of data, eg ":,1:2,0:3"
                sectionSpec = Objects.isNull(sectionSpec) ? ":,:" : sectionSpec;
                Array data = tem.read(sectionSpec);
                String arrayStr = Ncdump.printArray(data, "TEM", null);
                logger.info(arrayStr);
                return arrayStr;
            } catch (IOException | InvalidRangeException e) {
                logger.error(e.getMessage(), e);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }
}
